package com.chaofan.sell.controller;

import com.chaofan.sell.converter.OrderForm2OrderDTOConverter;
import com.chaofan.sell.dto.OrderDTO;
import com.chaofan.sell.enums.Result;
import com.chaofan.sell.exception.SellException;
import com.chaofan.sell.form.OrderForm;
import com.chaofan.sell.service.BuyerService;
import com.chaofan.sell.service.OrderService;
import com.chaofan.sell.utils.ResultVOUtil;
import com.chaofan.sell.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: Fairy
 * @date: 2021/9/8
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private BuyerService buyerService;

    /**
     * 创建订单
     *
     * @param orderForm     信息表单
     * @param bindingResult 处理结果
     * @return 处理结果json
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确，orderForm={}", orderForm);
            throw new SellException(Result.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车不能为空");
            throw new SellException(Result.CART_EMPTY);
        }
        OrderDTO create = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("orderId", create.getOrderId());

        return ResultVOUtil.success(map);

    }

    /**
     * 查询订单列表
     *
     * @param openid 买家微信openid
     * @param page   页数
     * @param size   长度
     * @return 查找结果json
     */
    @GetMapping("/list")
    public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
                                         @RequestParam(value = "page", defaultValue = "0") Integer page,
                                         @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (ObjectUtils.isEmpty(openid)) {
            log.error("【查询订单列表】openid为空");
            throw new SellException(Result.PARAM_ERROR);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "orderId");
        Pageable request = PageRequest.of(page, size, sort);
        Page<OrderDTO> orderDTOPage = orderService.findList(openid, request);
        return ResultVOUtil.success(orderDTOPage.getContent());
    }

    /**
     * 查询订单详情
     *
     * @param openid  买家微信openid
     * @param orderId 订单id
     * @return 订单信息json
     */
    @GetMapping("/detail")
    public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId) {
        if (ObjectUtils.isEmpty(openid)) {
            log.error("【查询订单详情】openid为空");
            throw new SellException(Result.PARAM_ERROR);
        }
        if (ObjectUtils.isEmpty(orderId)) {
            log.error("【查询订单详情】orderId为空");
            throw new SellException(Result.PARAM_ERROR);
        }
        OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
        return ResultVOUtil.success(orderDTO);
    }

    @PostMapping("/cancel")
    public ResultVO cancel(@RequestParam("openid") String openid, @RequestParam("orderId") String orderId) {
        if (ObjectUtils.isEmpty(openid)) {
            log.error("【取消订单】openid为空");
            throw new SellException(Result.PARAM_ERROR);
        }
        if (ObjectUtils.isEmpty(orderId)) {
            log.error("【取消订单】orderId为空");
            throw new SellException(Result.PARAM_ERROR);
        }
        buyerService.cancelOrder(openid, orderId);
        return ResultVOUtil.success();
    }
}
